package com.zxy.supplier_system.server.utils.wechat.official

import com.zxy.supplier_system.server.utils.wechat.WechatApiErrorResponse
import com.zxy.supplier_system.server.utils.wechat.validate200WechatApiErrorResponse


data class SendTemplateMessageRequest(
    val touser: String,
    val template_id: String,
    val data: Map<String, DataItem>,
    val url: String?,
    val miniprogram: MiniprogramData?,
    val client_msg_id: String?,
) {
    data class MiniprogramData(
        val appid: String,
        val pagepath: String?,
    )

    data class DataItem(
        val value: String,
    )
}

fun WechatOfficialAccountHelper.sendTemplateMessage(
    openId: String,
    templateId: String,
    data: Map<String, String>,
    url: String? = null,
    miniprogram: SendTemplateMessageRequest.MiniprogramData? = null,
    clientMessageId: String? = null,
): WechatApiErrorResponse {
    val accessToken = getOrFetchAccessToken()
    val responseEntity = restTemplate.postForEntity(
        "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=$accessToken",
        SendTemplateMessageRequest(
            openId,
            templateId,
            data.map { it.key to SendTemplateMessageRequest.DataItem(it.value) }.toMap(),
            url,
            miniprogram,
            clientMessageId
        ),
        WechatApiErrorResponse::class.java
    )
    val body = responseEntity.body!!
    validate200WechatApiErrorResponse(body)
    return body
}